/*
* @file bsp_key.cpp
* @brief Key driver implementation file
* @author feiniao
* @version 1.0
* @date 2025-5-11
* @note This code is designed to work with ESP32-S3 and uses the ESP-IDF 5.2.3 framework.
*       It provides a key driver for handling key press events with anti-shake functionality.
*/


#include "bsp_key.h"

BSP_KEY::BSP_KEY(gpio_num_t key_gpio_num) : key_gpio_num(key_gpio_num) {
    gpio_config_t io_conf = {
        .pin_bit_mask = (1ULL << key_gpio_num),
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_DISABLE  // 禁用中断
    };
    gpio_config(&io_conf);
}

BSP_KEY::~BSP_KEY() {
    gpio_reset_pin(key_gpio_num);  // 重置GPIO引脚
}


int BSP_KEY::get_key_num() {
    if (gpio_get_level(key_gpio_num) == 0) {  // 按键按下（低电平）
        uint64_t now = esp_timer_get_time();
        if (!debounce && (now - last_press_time > 50000)) {  // 50ms防抖
            debounce = true;
            last_press_time = now;
            ESP_LOGI(TAG, "按键确认按下!");
            return (int)key_gpio_num;
        }
    } else {
        debounce = false;  // 按键释放
    }
    return 0;
}